'use strict';

var {Sequelize, DataTypes}=require('sequelize');
var {database,username,password,host,dialect}=require('./config')

var sequelize=new Sequelize(database,username,password,{
    host:host,
    dialect:dialect
});


function defineModel(name,attrs){
    var prop={};

    prop.id={
        type:DataTypes.BIGINT,
        primaryKey:true,
        autoIncrement:true
    }

    for(var key in attrs){
        var value=attrs[key];
        prop[key]=value;
    }

    prop.createdAt={
        type:DataTypes.BIGINT,
        allowNull:false
    };
    prop.updatedAt={
        type:DataTypes.BIGINT,
        allowNull:false
    };
    prop.version={
        type:DataTypes.INTEGER,
        allowNull:false
    };
    prop.remarks={
        type:DataTypes.STRING(800),
        allowNull:true
    };


    var User=sequelize.define(name,prop,{
        tableName:name,
        timestamps:false,
        hooks:{
      
            beforeValidate:function(obj){
                var nw=Date.now();
                if(obj.isNewRecord){
                    obj.createdAt=nw;
                    obj.updatedAt=nw;
                    obj.version=0;
                }else{
                    obj.updatedAt=nw;
                    obj.version+=1;
                }
            }
        }
    });


    return User;
}

var obj={
    sequelize,
    defineModel,
    DataTypes
}

module.exports=obj;